from selenium import webdriver
from selenium.common.exceptions import WebDriverException, NoSuchElementException
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.edge.options import Options as EdgeOptions

from utils.log_utils import log  # 确保日志工具正确导入
import os
import time


class DriverFactory:
    @staticmethod
    def get_driver(browser=None, options=None, max_retries=2, retry_interval=3):
        """
        获取浏览器驱动实例（使用本地驱动，带重试机制）
        :param browser: 浏览器类型 (chrome/firefox/edge)
        :param options: 浏览器选项
        :param max_retries: 最大重试次数
        :param retry_interval: 重试间隔(秒)
        :return: WebDriver实例
        """
        # 确定浏览器类型，默认使用Chrome
        browser = (browser or "chrome").lower()
        driver = None
        
        # 项目根目录路径（根据实际目录结构调整）
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        # 驱动存放目录（framework1/drivers/）
        drivers_dir = os.path.join(project_root, "drivers")

        # 验证驱动目录是否存在
        if not os.path.exists(drivers_dir):
            raise FileNotFoundError(f"驱动目录不存在，请创建: {drivers_dir}")

        for retry in range(max_retries + 1):
            try:
                if browser == "chrome":
                    # Chrome驱动路径
                    driver_path = os.path.join(drivers_dir, "chromedriver.exe")
                    chrome_options = options or ChromeOptions()
                    
                    # 基础配置
                    chrome_options.add_argument("--ignore-certificate-errors")
                    chrome_options.add_argument("--disable-gpu")
                    chrome_options.add_argument("--no-sandbox")
                    chrome_options.add_argument("--disable-dev-shm-usage")
                    chrome_options.add_argument("--start-maximized")  # 最大化窗口
                    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
                    
                    # 验证驱动文件
                    if not os.path.exists(driver_path):
                        raise FileNotFoundError(f"Chrome驱动不存在: {driver_path}\n请下载对应版本放到该目录")

                    log.info(f"初始化Chrome驱动（第{retry+1}次尝试），路径: {driver_path}")
                    driver = webdriver.Chrome(
                        service=ChromeService(executable_path=driver_path),
                        options=chrome_options
                    )

                elif browser == "firefox":
                    # Firefox驱动路径
                    driver_path = os.path.join(drivers_dir, "geckodriver.exe")
                    firefox_options = options or FirefoxOptions()
                    
                    firefox_options.add_argument("--ignore-certificate-errors")
                    firefox_options.add_argument("--start-maximized")

                    if not os.path.exists(driver_path):
                        raise FileNotFoundError(f"Firefox驱动不存在: {driver_path}")

                    log.info(f"初始化Firefox驱动（第{retry+1}次尝试），路径: {driver_path}")
                    driver = webdriver.Firefox(
                        service=FirefoxService(executable_path=driver_path),
                        options=firefox_options
                    )

                elif browser == "edge":
                    # Edge驱动路径
                    driver_path = os.path.join(drivers_dir, "msedgedriver.exe")
                    edge_options = options or EdgeOptions()
                    
                    edge_options.add_argument("--ignore-certificate-errors")
                    edge_options.add_argument("--start-maximized")

                    if not os.path.exists(driver_path):
                        raise FileNotFoundError(f"Edge驱动不存在: {driver_path}")

                    log.info(f"初始化Edge驱动（第{retry+1}次尝试），路径: {driver_path}")
                    driver = webdriver.Edge(
                        service=EdgeService(executable_path=driver_path),
                        options=edge_options
                    )

                else:
                    raise ValueError(f"不支持的浏览器: {browser}，支持: chrome/firefox/edge")

                # 初始化成功
                log.info(f"{browser}驱动初始化成功")
                return driver

            except WebDriverException as e:
                log.warning(f"{browser}驱动初始化失败（第{retry+1}次）: {str(e)}")
                if retry < max_retries:
                    time.sleep(retry_interval)
            except Exception as e:
                log.error(f"未知错误（第{retry+1}次）: {str(e)}")
                if retry < max_retries:
                    time.sleep(retry_interval)

        # 所有重试失败
        raise WebDriverException(f"经过{max_retries+1}次尝试，{browser}驱动仍无法初始化")
    